<?php
/*
* 导出为一个数组，serive为key，包含method[req] method[resp]
 */
function get_out_dump($src) {
	$out = array();
	$lines = preg_split('/\n/', $src);
	foreach($lines as $line) {
		$matches = array();
		$preg = '/->(\d+\.\d+\.\d+\.\d+):(\d+)\|\|(.+)/';
		preg_match($preg, $line, $matches);
		if(!isset($matches[1]) || !isset($matches[2]) || !isset($matches[3])) {
			continue ;
		}
		
		$ip = $matches[1];
		$port = $matches[2];
		$ret = $matches[3];
		if(empty($ret)) {
			continue;
		}

		$obj = json_decode($ret, true);
		if(json_last_error()!=JSON_ERROR_NONE) {
			continue;
		}

		if(!is_array($obj)) {
			continue;
		}
		
		$svr = $obj['service'];
		$method = $obj['method'];

		//去重,已经存在了的忽略掉
		if(array_key_exists($svr, $out) && 
			isset($out[$svr][$method]) && 
			isset($out[$svr][$method]['req']) && 
			isset($out[$svr][$method]['resp'])) {
			continue ;
		}

		if(array_key_exists('result', $obj) && !isset($out[$svr][$method]['resp'])) {
			$out[$svr][$method]['resp'] = $ret;	
		}else if(!isset($out[$svr][$method]['req'])) {
			$out[$svr][$method]['req'] = $ret;
			$out[$svr][$method]['ip'] = $ip;	
			$out[$svr][$method]['port'] = $port;	
		}
	}

	return $out;
}

function handler($in) {
	if(empty($in)) {
		return ;
	}

	$con = mysql_connect("10.1.48.26","root","De4FKhOw?YZWPHdjst5ekr");
	mysql_query("SET NAMES UTF8");
	$out = get_out_dump($in);

	foreach ($out as $key => $value) {
		$srv = $key;
		foreach ($value as $k => $v) {
			$req = isset($v['req'])? $v['req']: "";
			$resp = isset($v['resp'])? $v['resp']: "";
			$ip = isset($v['ip'])? $v['ip']: "";
			$port = isset($v['port'])? $v['port']: "";
			$method = $k;

			$sql = "SELECT Fid FROM dev_db.t_auto_fsof_case WHERE Fservice='$srv' AND Fmethod='$method' AND Frequest<>'' AND Fresponse<>''";
			$result = mysql_query($sql,$con);
			$row = mysql_fetch_array($result,MYSQL_ASSOC);              
			/*
			if($row !=false && count($row)>0) {
				continue;	
			}
			 */

			$sql = "INSERT INTO dev_db.t_auto_fsof_case SET Fservice='$srv', Frequest='$req', Fresponse='$resp',Fip='$ip', Fport=$port, Fmethod='$method', Fowner='system', Fcreate_time=NOW()";
			echo $sql .PHP_EOL;
			//$result = mysql_query($sql,$con);
		}
	}
}
